﻿#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ease.EaseNode.Runtime
{
    public class CommonNodeDataManager<T> : INodeDataManager where T : IEaseNodeData
    {
        private List<Type> dataTypes = new List<Type>();

        private List<T> datas = new List<T>();

        private List<IEaseNodeDataState> states = new List<IEaseNodeDataState>();

        public List<IEaseNodeDataState> States => states;

        public event Action<T> OnDataCreateEvent;

        public CommonNodeDataManager(List<T> datas, List<Type> dataTypes)
        {
            this.datas = datas;
            this.dataTypes = dataTypes;
        }

        ~CommonNodeDataManager()
        {
            OnDataCreateEvent = null;
        }

        public void PrepareAllDataState(Action<IEaseNodeDataState> callback)
        {
            states.Clear();
            foreach (var baseDialogData in datas)
            {
                var temp = baseDialogData.CreateState();
                states.Add(temp);
            }

            foreach (var dialogDataState in states)
            {
                callback(dialogDataState);
            }
        }

        public IEaseNodeDataState AddNewData(Type type)
        {
            var target = dataTypes.FirstOrDefault(x => x == type);
            if (target != null)
            {
                if (Activator.CreateInstance(target) is T data)
                {
                    OnDataCreateEvent?.Invoke(data);
                    data.OnCreate();
                    var dataState = data.CreateState();
                    dataState.OnCreate();
                    datas.Add(data);
                    states.Add(dataState);
                    return dataState;
                }
            }

            return null;
        }

        public void RemoveOneData(string key)
        {
            foreach (var baseDialogData in datas)
            {
                if (baseDialogData.Key.Equals(key))
                    baseDialogData.OnDestroy();
            }

            foreach (var dialogDataState in states)
            {
                if (dialogDataState.Key.Equals(key))
                    dialogDataState.OnDestroy();
            }

            states.RemoveAll(x => x.Data == null);
            datas.RemoveAll(x => x.Key.Equals(key));
        }
    }
}
#endif